# - 多进程锁, 多线程锁都要自己实现一遍
# - 多进程通过Queue来实现进程通信
# - 把上述概念熟记并理解
from multiprocessing import Process, Lock
from multiprocessing import Queue
from threading import Thread
my_result = 0
my_thread_lock = Lock()


def my_save_file(index, lock):
    with lock:
        with open("test.txt", "a", encoding="utf-8") as f:
            f.write(str(index) + "\n")


def my_save_queue(index, my_queue):
    global my_result
    my_queue.put(str(index))
    for i in range(10**5):
        with my_thread_lock:
             my_result += 1
             my_result -= 1


def my_process():  # 测试进程通过文件通讯
    process_array = []
    lock = Lock()
    for i in range(4):
        p = Process(target=my_save_file, args=(i, lock))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    print("多进程已完成!已生成TXT文件")


def my_thread():  # 测试线程通过Queue来通讯
    thread_array = []
    my_queue = Queue()
    for i in range(3):
        t = Thread(target=my_save_queue, args=(i, my_queue))
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
    for r in range(my_queue.qsize()):
        print("多线程已完成!,打印消息队列结果:" + my_queue.get())


if __name__ == "__main__":
    my_process()
    my_thread()
    print(f'最后计算结果为:{my_result}')
